/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ai;

/**
 *
 * @author root
 */
public class IndexExp extends LexExp {
    public IndexExp(){
    }
    public IndexExp(LabelExp pLabel, String pRange){
        mLabel = pLabel;
        this.setRange(pRange);
    }
    public void setLabel(LabelExp pExp){
        mLabel = pExp;
    }
    public void setRange(String pRange){
        if(pRange.matches("-?[0-9]+")){
            mFrom = Integer.parseInt(pRange);
            mTo = mFrom;
        }
        else if(pRange.matches("(\\.\\.)-?[0-9]+")){
            String lStr = pRange.substring(2);
            mFrom = 0;
            mTo = Integer.parseInt(lStr);
        }
        else if(pRange.matches("-?[0-9]+(\\.\\.)")){
            String lStr = pRange.substring(0,pRange.length()-2);
            mFrom = Integer.parseInt(lStr);
            mTo = -1;
        }
        else if(pRange.matches("-?[0-9]+(\\.\\.)-?[0-9]+")){
            String lSplit[] = pRange.split("\\.\\.");
            mFrom = Integer.parseInt(lSplit[0]);
            mTo = Integer.parseInt(lSplit[1]);
        }
        //System.out.println("IndexExp.setRange(" + pRange  + ") mFrom = " + mFrom + "mTo = " + mTo );
    }
    public LexExp substitute(String pLabelName, String pString){
        if(mLabel.getName().equals(pLabelName)){
            int lFrom = Mod(mFrom, pString.length());
            int lTo = Mod(mTo, pString.length());

            StringExp lSubString = null;
            if (lFrom <= lTo){
                lSubString = new StringExp(pString.substring(lFrom, lTo + 1));
            }
            else {
                lSubString = new StringExp(pString.substring(lTo, pString.length()) + pString.substring(0, lFrom + 1));
            }
            //System.out.println("IndexExp.substitute( " + pLabelName + ", " + pString + " ) lSubString = " + lSubString );
            return lSubString;
        }
        else {
            return this;
        }
    }
    
    public String toString(){
        return mLabel.toString() + "[" + mFrom + ".." + mTo + "]";
    }
    
    private int Mod(int x, int y){
        if (y < 0){
            y = -y;
        }
        
        if (x >= 0){
            return x % y;
        }
        else {
            return y - (-x) % y;
        }
    }
    
    private LabelExp mLabel;
    private int mFrom,mTo;

}
